package logic

import (
	"context"
	"day15/api/pkg"
	"day15/model/redis"
	"day15/rpc/user"

	"day15/api/internal/svc"
	"day15/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdatePwdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserUpdatePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdatePwdLogic {
	return &UserUpdatePwdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserUpdatePwdLogic) UserUpdatePwd(req *types.UserUpdatePwdRequest) (resp *types.ApiResponse, err error) {
	// todo: add your logic here and delete this line
	key := "SMS-" + req.From + "-" + req.Phone
	redisCode, err := redis.Rdb.Get(key).Result()
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "验证码已过期",
			Data: nil,
		}, nil
	}
	if redisCode != req.Code {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "验证码错误",
			Data: nil,
		}, nil
	}
	if req.Password != req.RePassword {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "两次密码输入不一致",
			Data: nil,
		}, nil
	}

	_, err = l.svcCtx.UserSrv.UserUpdatePwd(l.ctx, &user.UserUpdatePwdReq{
		Phone:    req.Phone,
		Password: pkg.Md5Password(req.Password),
	})
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "密码重置失败",
			Data: nil,
		}, nil
	}
	return &types.ApiResponse{
		Code: 200,
		Msg:  "密码重置成功",
		Data: nil,
	}, nil

}
